package jiwei.config;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//文件上传拦截器
public class FileInterceptor3 implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        // 判断是否为文件上传请求
        if (req instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartReq = (MultipartHttpServletRequest) req;
            Map<String, MultipartFile> files = multipartReq.getFileMap();

            for (String formKey : files.keySet()) {
                MultipartFile multipartFile = multipartReq.getFile(formKey);
                byte[] file = multipartFile.getBytes();

                //获取字节流前8字节，差不多够了，不行再加
                int HEADER_LENGTH = 8;

                if (file.length > HEADER_LENGTH) {
                    //转成16进制
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < HEADER_LENGTH; i++) {
                        int v = file[i] & 0xFF;
                        String hv = Integer.toHexString(v);
                        if (hv.length() < 2) {
                            sb.append(0);
                        }
                        sb.append(hv);
                    }

                    boolean isFound = false;
                    String fileHead = sb.toString().toUpperCase();
                    List<String> headerList = new ArrayList<>();
                    for (String header : headerList) {
                        if (fileHead.startsWith(header)) {
                            isFound = true;
                            break;
                        }
                    }
                    if (!isFound) {
//                        throw new BaseRunException("上传文件有异常，已被系统禁止！") ;
                        System.out.println("----------上传文件有异常，已被系统禁止！头部信息：" + fileHead);
                        resp.setCharacterEncoding("UTF-8");
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter printWriter = resp.getWriter();
                        printWriter.write("上传文件有异常，已被系统禁止！");
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
